package com.example.util;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * <p></p>
 * Created by zhezhiyong@163.com on 2018/7/27.
 */
public class MD5Util {
    /**
     * 获得某个文件的MD5值
     */
    public static String getFileMD5(File srcFile) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(srcFile);
            byte[] buffer = new byte[1024];
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            int numRead = 0;
            while ((numRead = fis.read(buffer)) > 0) {
                md5.update(buffer, 0, numRead);
            }
            return toHexString(md5.digest());
        } catch (Exception e) {
            return "";
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    /**
     * 获得16进制字符串
     */

    public static String toHexString(byte[] datas) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < datas.length; i++) {
            String hex = Integer.toHexString(datas[i] & 0xFF);
            if (hex.length() <= 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
